package com.sphd.beautysalon.activitys;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sphd.beautysalon.activitys.foods.FoodtypeActivity;
import com.sphd.beautysalon.activitys.funding.FundingMangerActivity;
import com.sphd.beautysalon.activitys.manager.DianzhangListActivity;
import com.sphd.beautysalon.activitys.marking.MarketingActivity;
import com.sphd.beautysalon.activitys.order.WaiterAddOrdersActivity;
import com.sphd.beautysalon.activitys.staff.StaffActivity;
import com.sphd.beautysalon.activitys.vip.VipActivity;
import com.sphd.beautysalon.base.DialogAdapter;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.presenter.UserHomePresenterImpl;
import com.sphd.beautysalon.utils.AppManager;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.UserHomeView;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.activitys.funding.FundingPersonageActivity;
import com.sphd.beautysalon.activitys.kuncun.InOrOutRecordActivity;
import com.sphd.beautysalon.activitys.push.PushMoneyActivity;
import com.sphd.beautysalon.activitys.sale.RestaurantSalesActivity;
import com.sphd.beautysalon.base.BaseActivity;
import com.wzh.frame.views.RoundImageView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 店铺首界面
 */
public class UserHomeActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, UserHomeView, AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.restaurant_img)
    ImageView restaurantImg;
    @BindView(R.id.dayorder_textview)
    TextView dayorderTextview;
    @BindView(R.id.month_textview)
    TextView monthTextview;
    @BindView(R.id.daytoup_textview)
    TextView daytoupTextview;
    @BindView(R.id.suntoup_textview)
    TextView suntoupTextview;
    @BindView(R.id.supper_message_linear)
    LinearLayout supperMessageLinear;
    @BindView(R.id.content_user_home)
    LinearLayout contentUserHome;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.member_tv)
    TextView memberTv;
    @BindView(R.id.food_tv)
    TextView foodTv;
    @BindView(R.id.cashier_tv)
    TextView cashierTv;
    @BindView(R.id.spend_tv)
    TextView spendTv;
    @BindView(R.id.orders_tv)
    TextView ordersTv;
    @BindView(R.id.statist_tv)
    TextView statistTv;
    @BindView(R.id.market_tv)
    TextView marketTv;
    @BindView(R.id.staff_tv)
    TextView staffTv;
    @BindView(R.id.push_tv)
    TextView pushTv;
    @BindView(R.id.inorout_tv)
    TextView inoroutTv;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.change_restaurant)
    ImageView changeRestaurant;
    @BindView(R.id.toup_money)
    LinearLayout toupMoney;
    @BindView(R.id.restaurant_message)
    TextView restaurantMessage;
    private Intent intent;
    private Bundle bundle;
    private RestaurantInfo restaurantInfo;
    private LoginInfo loginInfo;
    private static final String TAG = "UserHomeActivity";
    private LinearLayout headLayout;
    private View headerView;
    private RoundImageView roundView;
    private TextView userName, userPermission, managerNav, goRestaurantNav, addRestaurantNav, myFuding, crowdfundingmanger;
    private UserHomePresenterImpl userPresenter;
    private DialogAdapter dialogAdapter;
    List<RestaurantInfo> restaurantInfoList;
    private View view;
    private ListView listView;
    double account=0;
    double daytopup,sumtopup;
    private Integer[] two_supper = {
            1, 2, 3,
            11, 13, 14,
            21, 22, 23,
             33, 34,
            41};
    private Integer[] three_manager = {
            2,
            13, 14,
            21, 22, 23,
             33, 34,
            41};
    private Integer[] four_receiver = {
            12, 15,
            21,

            41};
    private Integer[] five_waiter = {
            12, 15,
            23,
            41
    };
    private Integer[] six_investor = {
            5,
            13, 14
    };

    ActionBarDrawerToggle toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_home);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        headLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.setClass(context, MyselfSettingActivity.class);
                startActivity(intent);
            }
        });
        mySwf.setOnRefreshListener(this);
        navView.setNavigationItemSelectedListener(this);
        managerNav.setOnClickListener(this);
        goRestaurantNav.setOnClickListener(this);
        addRestaurantNav.setOnClickListener(this);
        crowdfundingmanger.setOnClickListener(this);
        myFuding.setOnClickListener(this);
        listView.setOnItemClickListener(this);
    }


    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        userPresenter = new UserHomePresenterImpl(this);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);

        loginInfo = DataSupport.findLast(LoginInfo.class);
        headerView = navView.getHeaderView(0);


        initHeader();
        initHeaderMenu();
        initAdapter();
        setUser();
        addData();
    }

    private void initAdapter() {
        restaurantInfoList = new ArrayList<>();
        dialogAdapter = new DialogAdapter(this, restaurantInfoList);
        view = setDialog(R.layout.dialog_list);
        listView = (ListView) view.findViewById(R.id.my_lsitView);
        listView.setAdapter(dialogAdapter);
    }

    private void addData() {
        userPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.Restaurantmessage + "cgid=" + restaurantInfo.getId());
        userPresenter.getMoney(RestaurantUrl.Httptitle + RestaurantUrl.HomeMoney + "cgid=" + restaurantInfo.getId());
    }

    private void initHeaderMenu() {
        managerNav = (TextView) headerView.findViewById(R.id.nav_restaurant_mangers);
        goRestaurantNav = (TextView) headerView.findViewById(R.id.nav_restaurant);
        addRestaurantNav = (TextView) headerView.findViewById(R.id.nav_add_restaurant);
        crowdfundingmanger = (TextView) headerView.findViewById(R.id.nav_crowdfundingmanger);
        myFuding = (TextView) headerView.findViewById(R.id.nav_myfunding);
    }

    private void initHeader() {
        headLayout = (LinearLayout) headerView.findViewById(R.id.nav_head_linear);
        roundView = (RoundImageView) headerView.findViewById(R.id.imageView_title);
        userName = (TextView) headerView.findViewById(R.id.username_textview);
        userPermission = (TextView) headerView.findViewById(R.id.permissions_textview);
        setImage(roundView, loginInfo.getStaff_photo());

        userName.setText(loginInfo.getStaff_name());
        userPermission.setText(loginInfo.getStaff_auth() == 2 ? "超管" : loginInfo.getStaff_auth() == 3 ? "店长" : loginInfo.getStaff_auth() == 4 ? "接单员" : loginInfo.getStaff_auth() == 5 ? "服务员" : "投资人");
    }

    /**
     * @param view
     */
    @OnClick({R.id.member_tv, R.id.food_tv, R.id.cashier_tv,
            R.id.spend_tv, R.id.orders_tv, R.id.statist_tv, R.id.market_tv, R.id.staff_tv, R.id.push_tv, R.id.inorout_tv,
            R.id.change_restaurant, R.id.dayorder_textview, R.id.month_textview,R.id.daytoup_textview,R.id.suntoup_textview})
    public void onClick(View view) {
        bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfo);
        intent.putExtras(bundle);
        switch (view.getId()) {
            case R.id.daytoup_textview:
                //日充值
                bundle.putDouble(Constant.ACCOUNT,account);
                bundle.putString(Constant.DAYTOP, String.valueOf(daytopup));
                bundle.putString(Constant.SUNTOP, String.valueOf(sumtopup));
                bundle.putInt(Constant.TYPE,0);
                intent.putExtras(bundle);
                intent.setClass(context,RechargeActivity.class);
                startActivity(intent);
                break;
            case R.id.suntoup_textview:
                //日充值
                bundle.putDouble(Constant.ACCOUNT,account);
                bundle.putString(Constant.DAYTOP, String.valueOf(daytopup));
                bundle.putString(Constant.SUNTOP, String.valueOf(sumtopup));
                bundle.putInt(Constant.TYPE,1);
                intent.putExtras(bundle);
                intent.setClass(context,RechargeActivity.class);
                startActivity(intent);
                break;
            case R.id.member_tv:
                //会员
                intent.setClass(context, VipActivity.class);
                startActivity(intent);
                break;
            case R.id.food_tv:
                //商品
                intent.setClass(context, FoodtypeActivity.class);
                startActivity(intent);
                break;
            case R.id.cashier_tv:
                //下单
                intent.setClass(context, WaiterAddOrdersActivity.class);
                startActivity(intent);
                break;
            case R.id.spend_tv:

                break;
            case R.id.orders_tv:
                //接单
                intent.setClass(context, AllOrdersActivity.class);
                startActivityForResult(intent,1);
                break;
            case R.id.statist_tv:
                break;
            case R.id.market_tv:
                //营销
                intent.setClass(context, MarketingActivity.class);
                startActivity(intent);
                break;
            case R.id.staff_tv:
                //员工
                intent.setClass(context, StaffActivity.class);
                startActivity(intent);
                break;
            case R.id.push_tv:
                //41提成
                intent.setClass(context, PushMoneyActivity.class);
                startActivity(intent);
                break;
            case R.id.inorout_tv:

                //库存
                intent.setClass(context, InOrOutRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.change_restaurant:
                //切换店铺
                setResult(0);
                finish();
                break;
            case R.id.nav_restaurant_mangers:
                //店长管理
                intent.setClass(context, DianzhangListActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_restaurant:
                //店铺信息编辑
                bundle.putSerializable(Constant.RESTAURANTSINFO,restaurantInfo);
                intent.putExtras(bundle);
                intent.setClass(context, RestaurantActivity.class);
                startActivityForResult(intent,1);
                break;
            case R.id.nav_add_restaurant:
                //开新店
                addRestauranDialog();
                break;
            case R.id.nav_crowdfundingmanger:
                showResList();
                break;
            case R.id.nav_myfunding:
                //权限6 我的众筹
                intent.setClass(context, FundingPersonageActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.dayorder_textview:
                //天的销售量
                bundle.putInt(Constant.TYPE, 0);
                intent.putExtras(bundle);
                intent.setClass(context, RestaurantSalesActivity.class);
                startActivity(intent);
                break;
            case R.id.month_textview:
                //月销售量
                bundle.putInt(Constant.TYPE, 1);
                intent.putExtras(bundle);
                intent.setClass(context, RestaurantSalesActivity.class);
                startActivity(intent);
                break;
        }
    }


    /**
     * 显示新增店铺的提示框
     */
    private void addRestauranDialog() {
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.layout_edittextdialog, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        alertDialogBuilder.setTitle("新增分店数量:");
        alertDialogBuilder.setView(promptsView);

        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.input);
        userInput.setHint("");
        userInput.setInputType(2);//为数字
        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result
                                // edit text
                                if (!TextUtils.isEmpty(userInput.getText())) {
                                    userPresenter.addRestaurant(RestaurantUrl.Httptitle +
                                            RestaurantUrl.AddRestaurantFen
                                            + "hqid=" + loginInfo.getStaff_cgid()
                                            + "&nownumber=" + loginInfo.getCgnumber()
                                            + "&addnumber=" + userInput.getText()
                                            + "&superid=" + loginInfo.getSuperid());
                                } else {
                                    Toast.makeText(context, "输入分店数量为空", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }


    private void showResList() {

        userPresenter.getResList(RestaurantUrl.Httptitle + RestaurantUrl.RESTAURANTS + "cgid=" + loginInfo.getStaff_cgid());
    }

    @Override
    public void recRes(int res) {
        if (res == 1) {
            toast("提交成功，请等待审核");
        } else {
            toast("提交失败，请稍后再试！");
        }
    }

    @Override
    public void receiveRes(List<RestaurantInfo> restaurantInfos) {
        this.restaurantInfoList.clear();
        this.restaurantInfoList.addAll(restaurantInfos);
        dialogAdapter.notifyDataSetChanged();
        showResesDialog();

    }

    private void setUser() {
//        List<Integer> integerList = new ArrayList<>();
        List<Integer> integerList = Arrays.asList(two_supper);

        if (isSuperManager(loginInfo)) {
            integerList = Arrays.asList(two_supper);

        } else if (isManager(loginInfo)) {
            integerList = Arrays.asList(three_manager);

        } else if (isReciver(loginInfo)) {
            integerList = Arrays.asList(four_receiver);

        } else if (isWaiter(loginInfo)) {
            integerList = Arrays.asList(five_waiter);

        } else  if (isFundinger(loginInfo)){
            integerList= Arrays.asList(six_investor);
        }

        // TODO: 2016/11/2  遍历对应的list 获取控件是显示还是隐藏
        for (Integer integer : integerList) {
            Log.e(TAG, integer + "");
            if (integer == 1) {
                //是否能编辑店长  //店长管理
                managerNav.setVisibility(View.VISIBLE);
            } else if (integer == 2) {
                //查看店铺信息
                goRestaurantNav.setVisibility(View.VISIBLE);
            } else if (integer == 3) {
                //开新店
                addRestaurantNav.setVisibility(View.VISIBLE);
            } else if (integer == 4) {
                //投资管理 （原众筹）
                crowdfundingmanger.setVisibility(View.VISIBLE);
            } else if (integer == 5) {
                //我的众筹
                myFuding.setVisibility(View.VISIBLE);
            } else if (integer == 11) {
                //切换店铺
                changeRestaurant.setVisibility(View.VISIBLE);
            } else if (integer == 12) {
                //查看店铺的图像（用于在不能查看销售额的时候显示）
                restaurantImg.setVisibility(View.VISIBLE);
            } else if (integer == 13) {
                //查看店铺的销售额
                supperMessageLinear.setVisibility(View.VISIBLE);
            } else if (integer == 14) {
                //查看充值金额
                toupMoney.setVisibility(View.VISIBLE);
            } else if (integer == 15) {
                restaurantMessage.setVisibility(View.VISIBLE);
            } else if (integer == 21) {
                //会员信息
                setIcImage(R.mipmap.ic_member, memberTv);
            } else if (integer == 22) {
                //商品信息
                setIcImage(R.mipmap.ic_dish, foodTv);
            } else if (integer == 23) {
                //下单
                setIcImage(R.mipmap.ic_cashier, cashierTv);
            } else if (integer == 24) {
                //支出
                setIcImage(R.mipmap.ic_spend, spendTv);
            } else if (integer == 31) {
                //接单
                setIcImage(R.mipmap.ic_order, ordersTv);
            } else if (integer == 32) {
                //分析
                setIcImage(R.mipmap.ic_statist, statistTv);
            } else if (integer == 33) {
                //营销
                setIcImage(R.mipmap.ic_market, marketTv);
            } else if (integer == 34) {
                //员工
                setIcImage(R.mipmap.ic_staff, staffTv);
            } else if (integer == 41) {
                //提成
                setIcImage(R.mipmap.userhome_push, pushTv);
            } else if (integer == 42) {
                //库存
                setIcImage(R.mipmap.ic_inorout_record, inoroutTv);
            }
        }

    }

    private void setIcImage(int ic_member, TextView tv) {
        tv.setEnabled(true);
        tv.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(
                ic_member), null, null);
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id) {
            case R.id.nav_changepassword://修改密码界面
                intent.setClass(context, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_share://二维码分享界面包括管理端和用户端
                intent.setClass(context, ShareEwmActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_about://关于中心
                intent.setClass(context, SettingActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void sendRes(List<RestaurantInfo> restaurantInfos, int resNo) {
        setImage(restaurantImg, restaurantInfos.get(0).getCg_pic());

        this.restaurantInfo = restaurantInfos.get(0);
        int hasManger=restaurantInfo.getStaff_status();
        Log.e("EEE==",hasManger+"");

//        setTitleBar(toolbar, restaurantInfo.getCg_name()!=null?restaurantInfo.getCg_name():"");
        restaurantMessage.setText("\t\t餐馆信息:\n" + restaurantInfos.get(0).getCg_intro());
        setTitleBar(toolbar, restaurantInfo.getCg_name() != null ? restaurantInfo.getCg_name() : "");
        toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();
        setImage(restaurantImg, restaurantInfo.getCg_pic());

    }

    @Override
    public void sendMoney(double sumtopup, double account, double daytopup, double sumorder, double dayorder) {
        dayorderTextview.setText(turn(dayorder));
        monthTextview.setText(turn(sumorder));
        this.account=account;
        this.daytopup=daytopup;
        this.sumtopup=sumtopup;
        daytoupTextview.setText("今日充值\n￥" + turn(daytopup));
        suntoupTextview.setText("本月充值\n￥" + turn(sumtopup));
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfoList.get(i));
        startActivity(FundingMangerActivity.class, bundle);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1){
            addData();
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        mySwf.setRefreshing(false);
        dissLoadingDialog();
    }

    @Override
    public void onRefresh() {
        addData();
    }
}
